package org.openmore.platform.pay.IAP;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.openmore.common.enums.Platform;
import org.openmore.platform.dto.common.BaseResponse;
import org.openmore.platform.pay.Payment;
import org.openmore.platform.pay.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IAPPayService implements PaymentService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**测试plaload*/
    //private String plyload="ewoJInNpZ25hdHVyZSIgPSAiQTUwV2NaT2t4OHJIM3lTbENtUUluR3BEcnJtZDVSMHdVaVBMOXloTlhKaFhpOElDcitraHdpdUU0SVd4QmhoRGV3a3pJUCswK2pUNmpSRVozTHNaUUlBR1dQWnorOVd5VnVPQ21tUldPVzczWG9zZzE4Y05EQnlpVGlCbmgvc1BnajQ4akVkVi9iVFN2UUx3L2IyYXJwWXBhMXlMSWpndm5PUEhRcGQvL0lXcmlkRUNuK0RBYkVzOGRlWW9jOVVFMXRDejlmcjB3Q3U5T0pIcm9ObURzQ1BvMEx2MVdXNUR2SnA1NythbWZENnprTW5YMy9Gd3NNSm1FM3kyVmtQbmdpanB4MVF0V2FGZTNvRmZac2ZpRHFOV3pLZUpjT0ZtSnRvSGRqanA5SHNPMEVGYnEzQnhaMS80ZTFhRHh4SU0wSXJ0c2xaWEtJUXNVc0VGRmQ0OXczc0FBQVdBTUlJRmZEQ0NCR1NnQXdJQkFnSUlEdXRYaCtlZUNZMHdEUVlKS29aSWh2Y05BUUVGQlFBd2daWXhDekFKQmdOVkJBWVRBbFZUTVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Td3dLZ1lEVlFRTERDTkJjSEJzWlNCWGIzSnNaSGRwWkdVZ1JHVjJaV3h2Y0dWeUlGSmxiR0YwY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QWlNQ0k3Q2draWFYTXRhVzR0YVc1MGNtOHRiMlptWlhJdGNHVnlhVzlrSWlBOUlDSm1ZV3h6WlNJN0Nna2ljSFZ5WTJoaGMyVXRaR0YwWlMxdGN5SWdQU0FpTVRVMk1ETXlNekUwT0RFeE9DSTdDZ2tpY0hWeVkyaGhjMlV0WkdGMFpTSWdQU0FpTWpBeE9TMHdOaTB4TWlBd056b3dOVG8wT0NCRmRHTXZSMDFVSWpzS0NTSnBjeTEwY21saGJDMXdaWEpwYjJRaUlEMGdJbVpoYkhObElqc0tDU0p2Y21sbmFXNWhiQzF3ZFhKamFHRnpaUzFrWVhSbElpQTlJQ0l5TURFNUxUQTJMVEV5SURBM09qQTFPalE0SUVWMFl5OUhUVlFpT3dvSkltSnBaQ0lnUFNBaVkyOXRMbnBvYjI1bmRHbGhiaTVSZFZCcGJtZEdZVzVuSWpzS0NTSndkWEpqYUdGelpTMWtZWFJsTFhCemRDSWdQU0FpTWpBeE9TMHdOaTB4TWlBd01Eb3dOVG8wT0NCQmJXVnlhV05oTDB4dmMxOUJibWRsYkdWeklqc0tmUT09IjsKCSJlbnZpcm9ubWVudCIgPSAiU2FuZGJveCI7CgkicG9kIiA9ICIxMDAiOwoJInNpZ25pbmctc3RhdHVzIiA9ICIwIjsKfQ==";

    @Override
    public BaseResponse payment(String host, String tenantId, Payment payment) throws Exception {
        return BaseResponse.buildSuccessResponse(payment);
    }
    /**
     * 苹果内购校验
     * @param userId 订单号
     * @param transactionId 苹果内购交易ID
     * @param payPrice 苹果内购交易价格
     * @param payload 校验体（base64字符串）
     * @return
     */
    @Transactional
    public BaseResponse payVerify(String tenantId, String orderNum, String userId, String transactionId, Long payPrice, String payload, Platform platform){
        if(null!=payPrice){
            payPrice=payPrice*100;
        }
        logger.info("苹果内购校验开始，交易ID：" + transactionId + " base64校验体：" + payload);
        //logger.debug("==>order userID:"+userId);
        /*List<CommonOrderDto> commonOrderDtos = commonOrderService.selectAll(null ,null, transactionId,
                null, null,null, null, null, null);
        if(!CollectionUtils.isEmpty(commonOrderDtos)){
            return BaseResponse.buildFailResponse(400, "订单已支付，请不要重复提交");
        }*/
        //TODO ::线上环境验证,上线改为1
        int testIpad = 0;//IPAD是否测试环境
        int testIphone = 1;//iPhone是否测试环境
        //是否是测试环境
        int ifTest = null == platform?0:(platform==Platform.IPAD?testIpad:testIphone);
        String verifyResult = IosVerifyUtil.buyAppVerify(payload, ifTest);
        if (verifyResult == null) {
            return BaseResponse.buildFailResponse(400,"苹果验证失败，返回数据为空");
        } else {
            logger.info("线上，苹果平台返回JSON:" + verifyResult);
            JSONObject appleReturn = JSONObject.parseObject(verifyResult);
            String states = appleReturn.getString("status");
            //无数据则沙箱环境验证
            if ("21007".equals(states)) {
                verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);
                logger.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
                appleReturn = JSONObject.parseObject(verifyResult);
                states = appleReturn.getString("status");
            }
            logger.info("苹果平台返回值：appleReturn" + appleReturn);
            // 前端所提供的收据是有效的    验证成功
            if (states.equals("0")) {
                String receipt = appleReturn.getString("receipt");
                JSONObject returnJson = JSONObject.parseObject(receipt);
                String inApp = returnJson.getString("in_app");
                if(StringUtils.isEmpty(inApp)){
                    //单商品购买
                    String appTransactionId = (String) returnJson.get("transaction_id");
                    String productId = (String) returnJson.get("product_id");
                    Integer quantity = Integer.valueOf((String) returnJson.get("quantity"));
                    quantity = null == quantity?1:quantity;
                    //交易列表包含当前交易，则认为交易成功
                    if(appTransactionId.equals(transactionId)){

                        return BaseResponse.buildSuccessResponse("购买成功");
                    }else{
                        return BaseResponse.buildFailResponse(400,"当前交易不在交易列表中");
                    }
                }else{
                    //商品列表购买
                    List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
                    if (!CollectionUtils.isEmpty(inApps)) {
                        ArrayList<String> transactionIds = new ArrayList<String>();
                        Map<String, String> productIds = new HashMap<>();
                        Map<String, Integer> productQuantities = new HashedMap();
                        for (HashMap app : inApps) {
                            String appTransactionId = (String) app.get("transaction_id");
                            transactionIds.add(appTransactionId);
                            //保存商品ID
                            productIds.put(appTransactionId, (String) app.get("product_id"));
                            //保存购买数量
                            productQuantities.put(appTransactionId, Integer.valueOf((String)app.get("quantity")));
                        }
                        //交易列表包含当前交易，则认为交易成功
                        if (transactionIds.contains(transactionId)) {
                            return BaseResponse.buildSuccessResponse("购买成功");
                        }
                        return BaseResponse.buildFailResponse(400,"当前交易不在交易列表中");
                    }
                    return BaseResponse.buildFailResponse(400, "未能获取获取到交易列表");
                }
            } else {
                return BaseResponse.buildFailResponse(400, "支付失败，错误码：" + states);
            }
        }
    }
}
